package com.ly.hotel.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.TimerTask;
import java.util.Vector;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.WindowManager;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.OkHttpStack;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.ly.hotel.R;
import com.ly.hotel.adaptor.AtvUtil;
import com.ly.hotel.common.Constants;
import com.ly.hotel.common.HandNoBinder;
import com.ly.hotel.common.MyApplication;
import com.ly.hotel.common.SharedConfBlacklight;
import com.ly.hotel.common.SharedPreferencesConfig;
import com.ly.hotel.common.SysConf;
import com.ly.hotel.model.AppInfo;
import com.ly.hotel.model.BackgroundInfo;
import com.ly.hotel.model.DeviceInfo;
import com.ly.hotel.model.Episodepart;
import com.ly.hotel.model.IconAnimationDetail;
import com.ly.hotel.model.LiveManagement;
import com.ly.hotel.model.ModelBean;
import com.ly.hotel.model.PluginCfgBean;
import com.ly.hotel.model.ScrollMessage;
import com.ly.hotel.model.SeatPicInfo;
import com.ly.hotel.model.StartUpGuideInfo;
import com.ly.hotel.model.SysSettingInfo;
import com.ly.hotel.model.TimingMsgBean;
import com.ly.hotel.model.Vodvideo;
import com.ly.hotel.model.YouhuiMessage;
import com.ly.hotel.model.MusicAlbumPageBean;
import com.ly.hotel.model.MusicPageBean;
import com.ly.hotel.model.VodVideoBean;
import com.ly.hotel.model.Vodpart;
import com.ly.hotel.msgevent.ActionTimeTickEvent;
import com.ly.hotel.msgevent.CloudPlayVideoEvent;
import com.ly.hotel.msgevent.GetAreaEvent;
import com.ly.hotel.msgevent.GetEpisodeVideoEvent;
import com.ly.hotel.msgevent.GetGameEvent;
import com.ly.hotel.msgevent.GetIntro;
import com.ly.hotel.msgevent.GetMusicEvent;
import com.ly.hotel.msgevent.GetScrollMessage;
import com.ly.hotel.msgevent.GetTimingMsgEvent;
import com.ly.hotel.msgevent.GetVodEpisodeListEvent;
import com.ly.hotel.msgevent.GetVodSearchVideoEvent;
import com.ly.hotel.msgevent.GetVodTypeListEvent;
import com.ly.hotel.msgevent.GetVodVideoEvent;
import com.ly.hotel.msgevent.GetWeatherEvent;
import com.ly.hotel.msgevent.GetWebInterfaceUrlEvent;
import com.ly.hotel.msgevent.GetYouhuiMsgEvent;
import com.ly.hotel.msgevent.AdShowFinishEvent;
import com.ly.hotel.msgevent.SetMsgShowFinishEvent;
import com.ly.hotel.msgevent.SetVodPlayEvent;
import com.ly.hotel.msgevent.MsgDialogEvent;
import com.ly.hotel.msgevent.SyncCallEvent;
import com.ly.hotel.msgevent.UpdateBlacklightEvent;
import com.ly.hotel.msgevent.UpdateBottomView;
import com.ly.hotel.msgevent.UpdateEpisodeTypeListEvent;
import com.ly.hotel.msgevent.UpdateEpisodeVideoEvent;
import com.ly.hotel.msgevent.UpdateGameListEvent;
import com.ly.hotel.msgevent.UpdateInterfaceEvent;
import com.ly.hotel.msgevent.UpdateIntro;
import com.ly.hotel.msgevent.UpdateMessageView;
import com.ly.hotel.msgevent.UpdateMusicEvent;
import com.ly.hotel.msgevent.UpdateVodSearchVideoEvent;
import com.ly.hotel.msgevent.UpdateVodTypeListEvent;
import com.ly.hotel.msgevent.UpdateVodVideoEvent;
import com.ly.hotel.msgevent.UpdateYouhuiMsgEvent;
import com.ly.hotel.timetask.CallStatusSyncTimerTask;
import com.ly.hotel.timetask.HeartbeatTimerTask;
import com.ly.hotel.timetask.MyCmdTimerTask;
import com.ly.hotel.timetask.ServerTimeTimerTask;
import com.ly.hotel.timetask.WeatherTimerTask;
import com.ly.hotel.util.FileUtils;
import com.ly.hotel.util.HttpHelper;
import com.ly.hotel.util.HttpRequestFailException;
import com.ly.hotel.util.ImageUtil;
import com.ly.hotel.adaptor.HardwareProperty;
import com.ly.hotel.adaptor.NetworkUtil;
import com.ly.hotel.adaptor.HardwareInterface;
import com.ly.hotel.adaptor.SoftwareProperty;
import com.ly.hotel.broadcast.TimingMsgReceiver;
import com.ly.hotel.util.InterfaceConfUtil;
import com.ly.hotel.view.common.CloudAdShowActivity;
import com.ly.hotel.view.common.MsgDialog;
import com.ly.hotel.view.common.TimingMsgDialog;
import com.ly.hotel.view.common.msg.MarqueeToast;
import com.ly.hotel.view.common.msg.IScrollState;
import com.ly.hotel.view.common.msg.TextSurfaceView;
import com.ly.hotel.webagent.HttpRequest;
import com.squareup.okhttp.OkHttpClient;

import de.greenrobot.event.EventBus;

public class SPABackService extends Service implements IScrollState, Runnable {
	private static final Gson gson = new GsonBuilder().create();
	private static int TOAST_WIDTH = 750;
	private static int TOAST_X = 265;
	private static int TOAST_Y = 10;
	private static MyApplication app;
	public static String zipCreatTime;
	private ThisHandler handlerMsg = new ThisHandler(this);

	private static final int HANDLER_CHECK_SERVER = -3;
	private static final int HANDLER_INIT = -2;
	private static final int HANDLER_SCROLL_MSG = 0;
	private static final int HANDLER_RT_MSG = 1;
	private static final int HANDLER_TIMING_MSG = 2;
	private static final int HANDLER_GET_TIMING_MSG = 3;
	public static final int INIT_CO_BOARD =  -4;
	public static final int SEND_CO_BOARD_HEART =  -5;
	public static final int INIT_SCROLL_MESSAGE =  22;
	
	// 消息滚动条
	private MarqueeToast toast;
	private int messageindex = 0;
	private TextSurfaceView scrollText;
	private int currentMsgId = -1;
	private int serverCheckTime = 3000;
	@SuppressLint("UseSparseArrays")
	public static HashMap<Integer, MsgDialog> msgActivity = new HashMap<>();
	public final static int MSG_ACTIVITY_BEGIN_ID = 1000;
	public static Integer msgActivityid = MSG_ACTIVITY_BEGIN_ID;
	private boolean getConfOK = false;//从服务器获取系统配置成功
	private static ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(6);//2会导致一些线程无法运行
	public static RequestQueue mQueue;
	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		app = (MyApplication) getApplication();
		Log.i("init-SPABackService", "SPABackService onCreate");
		// 接收事件
		EventBus.getDefault().register(this);

		handlerMsg.sendEmptyMessageDelayed(HANDLER_CHECK_SERVER, 100);
		
		OkHttpClient client = new OkHttpClient();
		mQueue = Volley.newRequestQueue(this, new OkHttpStack(client));
		mQueue.start();
	}


	public static ScheduledExecutorService getThreadPool() {
		return threadPool;
	}

	private void initGetLocalIp() {
		new Thread() {
			@Override
			public void run() {
				try {
					app.setMyIpAddr(getIpAddr());
					Log.i("initData", "获取IP成功:" + app.getMyIpAddr());
					initReportMyIP();			//上报本地IP
				} catch (SocketException e1) {
					Log.e("initData", "获取IP失败:" + e1.getMessage());
				}
			}
		}.start();
	}

	@SuppressLint("DefaultLocale")
	private String getIpAddr() throws SocketException {
		for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
			NetworkInterface intf = en.nextElement();
			if (intf.getName().toLowerCase().equals("eth0") || intf.getName().toLowerCase().equals("wlan0")) {
				for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					Log.i("ip", inetAddress.getHostAddress().toString());
					if (!inetAddress.isLoopbackAddress()) {
						String ipaddress = inetAddress.getHostAddress().toString();
						Log.i("ip", inetAddress.getHostAddress().toString());
						if (!ipaddress.contains("::") && ipaddress.length() <= 17) {// ipV6的地址
							return ipaddress;
						}
					}
				}
			} else {
				continue;
			}
		}
		return "";
	}

	public void co_borad_handler_init(){
		Log.i("co-board", "co_borad_handler_init");
		
		handlerMsg.sendEmptyMessageDelayed(SEND_CO_BOARD_HEART, 3000);
		handlerMsg.sendEmptyMessageDelayed(INIT_CO_BOARD, 1000);
	}
		
	public void checkServerAlive(){
	
		try {
			String url = MyApplication.getHost() + SPAService.PROJECT + "/api/now.json";
			
			StringRequest  stringRequest = new StringRequest(Request.Method.GET, url, 
	                 new Response.Listener<String>() {  
	                     @Override  
	                     public void onResponse(String response) {
	             			MyApplication.serverAssess = true;
							ModelBean d = gson.fromJson(response, ModelBean.class);

							if (d != null) {
								 if (!d.getCode().equals(-1) && d.getData() != null && !d.getData().equals("")){
									 app.nowTime = d.getData().toString();
								 }
							}
						 }
	                 }, new Response.ErrorListener() {
	                     @Override  
	                     public void onErrorResponse(VolleyError error) {  
	                    	 MyApplication.serverAssess = false;
	                    	 Log.e("alive", "获取本地服务器时间失败." + error.getMessage()); 
	                     }  
	                 }); 
			mQueue.cancelAll("alive");//清除之前的，否则会出错 socket failed: EMFILE (Too many open files)
			stringRequest.setTag("alive");
			stringRequest.setShouldCache(false);
			mQueue.add(stringRequest);
		} catch (Exception e) {
			Log.e("heart", "SPAService.heartbeat:" + e.getMessage());
		}
		
		//网络通了，才能初始化一系列的东西
		if(MyApplication.serverAssess){
			handlerMsg.sendEmptyMessageDelayed(HANDLER_INIT, 100);
		}else{
			/*serverCheckTime += 100;
			if(serverCheckTime > 30 * 60 * 1000){
				//30分钟之后，就恢复初始值，重新试
				serverCheckTime = 3000;
			}*/
			Log.i("heart", "服务器不通,尝试" + serverCheckTime + "毫秒之后重连.");
			handlerMsg.sendEmptyMessageDelayed(HANDLER_CHECK_SERVER, serverCheckTime);
		}

	}
		
	private void initServerApiVersion() {
		new Thread() {
			@Override
			public void run() {
				String version = SPAService.getServerApiVersion(MyApplication.getMAC());
				MyApplication.serverApiVersion = version;
				Log.i("initData", "服务器接口版本号:" + version);
			}
		}.start();
	}
	
	private void initSysSetting() { 
		Log.i("init-setting", "初始化系统配置");
		
		
		final AsyncHttpResponseHandler handler = new AsyncHttpResponseHandler() {
			
			SysSettingInfo si = null;
			
			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				Log.i("init-setting", "获取系统配置完成:" + new String(arg2));
				String result;
				File f = new File(Constants.SYS_CFG_FILE_PATH);
				File f_folder = new File(Constants.SYS_CFG_FILE_ROOT);
				
				if(arg2 != null){
					result = new String(arg2);
					ModelBean d = gson.fromJson(result, ModelBean.class);
					if (d != null && !d.getCode().equals(-1) && d.getData() != null) {
						si = (SysSettingInfo) d.getData(SysSettingInfo.class);
						if (si != null) {
							Log.i("init-setting", "保存系统设置到本地文件中.");
							// 检测目录是否存在，没有就新建之
							if (!f_folder.exists()) {
								f_folder.mkdirs();
							}
							// 新建文件
							try {
								f.createNewFile();
								FileWriter fw = new FileWriter(Constants.SYS_CFG_FILE_PATH);
								fw.write(result + "\r\n");
								fw.close();
							} catch (IOException e) {
								e.printStackTrace();
							}
						}
					}
				}else{
					Log.e("init-setting", "获取系统配置完成，但没有取得有效数据.");
				}
			}
			
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
				Log.e("init-setting", "获取系统配置失败:" + arg3.getMessage());
			}
	
			@Override
			public void onFinish() {
				Log.i("init-setting", "初始化系统配置。。。");
				File f = new File(Constants.SYS_CFG_FILE_PATH);
				if (f.exists()) {
					Log.i("init-setting", "通过本地文件初始化系统设置");
					// 通过本地文件设置按键配置
					InputStreamReader ir;
					try {
						ir = new InputStreamReader(new FileInputStream(Constants.SYS_CFG_FILE_PATH), "utf-8");
						BufferedReader bf = new BufferedReader(ir);
	
						String tempString = bf.readLine();
						ModelBean dd = gson.fromJson(tempString, ModelBean.class);
						if (dd != null) {
							si = (SysSettingInfo) dd.getData(SysSettingInfo.class);
						}
						// 一次读一行，读入null时文件结束
						bf.close();
	
					} catch (UnsupportedEncodingException e1) {
						e1.printStackTrace();
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				
	
				if (si != null) {
					Log.i("init-setting", "获取系统设置成功");
					Log.i("init-setting", "留位时间=" + si.getLiuweiWaitTime());
					if (si.getLiuweiWaitTime() >= 0 && si.getLiuweiWaitTime() <= 30) {
						app.setLiuweiTime(si.getLiuweiWaitTime());
					}
					Log.i("init-setting", "屏幕初始亮度=" + si.getDisplay());
					if(si.getDisplay() >= 0 && si.getDisplay() <= 100){
						SharedConfBlacklight.setAlpha(si.getDisplay()*2);
						MyApplication.softBlacklightValue = SharedConfBlacklight.getColor(200-si.getDisplay()*2,0,0,0);
						if(BacklightService.STATE == BacklightService.ACTIVE){
							EventBus.getDefault().post(new UpdateBlacklightEvent());
				    	}
					}
					Log.i("init-setting", "最大音量=" + si.getMaxVolume());
					
					if (si.getMaxVolume() >= 5 && si.getMaxVolume() <= 100) {
						/* 音量设置需要重启机器才生效 */
						Log.i("init-setting", "最大音量设进主板 begin=" + si.getMaxVolume());
						HardwareInterface.setMaxVolume(si.getMaxVolume());
						Log.i("init-setting", "最大音量设进主板 end=" + HardwareInterface.getMaxVolume());
					} else {
						Log.e("init-setting", "最大音量设置出错");
					}
					if (si.getLight() == 0) {
						app.enableServerLed = false;
					}
					if (si.getExtendconf() != null && !si.getExtendconf().equals("")) {
						try {
							SysConf.sysParse(si.getExtendconf());
							
							//获取完配置，重新设置一下默认音量
							Integer volume = Constants.STARTUP_VOLUME;
							volume = Integer.parseInt(SysConf.extendConfGetValue(SysConf.SYS_CONF_STARTUP_VOLUME, Constants.STARTUP_VOLUME+""));
							HardwareInterface.setVolume(volume);
							Log.i("init-setting", "使用服务器配置设置默认音量 -> " + volume);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
				
				getConfOK = true;
				
				super.onFinish();
			}
		};
		
		// 获取系统配置
		new Thread() {
			@Override
			public void run() {
				// 网络获取后，保存到本地文件 
				String url = MyApplication.getHost() + SPAService.PROJECT + "/api/deploy.json?mac=" + MyApplication.getMAC();
				HttpHelper.getStringAsync(getBaseContext(), url, null, handler);
			}
		}.start();
	}
	
	//同步云端服务器的数据
	private synchronized void startMyCloud() {
		if(!MyApplication.cloudStart){
			Log.i("initData","启动云service.........");
			Intent inteservice = new Intent(this, MyCloudBackService.class);
			this.startService(inteservice);
			MyApplication.cloudStart = true;
		}
	}
	
	private void initCloud(){
		Thread task = new Thread() {
			@Override
			public void run() {
				//要延时一下，等待系统配置数据获取完成按需要打开云
				int times = 6;
				try {
					while(!getConfOK && times>0){
						times--;
						Thread.sleep(1000);
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				
				if(SysConf.extendConfGetValue(SysConf.SYS_CONF_CLOUD_ENABLE, "1").equals("1")){
					Log.i("init", "云端开启");
					if(MyApplication.licenseTimeOut/* && MyApplication.ukeyInvalidDays >= 0*/){
						//notting
					} else {
						startMyCloud();
					}
				}else{
					Log.i("init", "云端关闭");
				}
			}
		};
		
		getThreadPool().schedule(task, 0, TimeUnit.MILLISECONDS);
	}

	private void initCoBoard(){
		Thread task = new Thread() {
			@Override
			public void run() {
				//要延时一下，等待系统配置数据获取完成按需要打开云
				int times = 3;
				try {
					while(!getConfOK && times>0){
						times--;
						Thread.sleep(1000);
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				
				String enable = SysConf.extendConfGetValue(SysConf.SYS_CONF_CO_BOARD_ENABLE, "1");
				if(enable.equals("1")){
					co_borad_handler_init();	//初始化协处理板和发送心跳给协处理板
				} else {
					Log.i("co-board", "禁止发心跳及复位协处理板.");
				}
			}
		};
		
		getThreadPool().schedule(task, 0, TimeUnit.MILLISECONDS);
	}

	private void initExpConf() {
		Thread task = new Thread() {
			@Override
			public void run() {
				Looper.prepare();
				try {
					SPAService.getExpSetting(MyApplication.getMAC());
					Log.i("initData", "获取扩展配置成功.");
				} catch (HttpRequestFailException e) {
					Log.e("initData", "获取扩展配置失败.");
					e.printStackTrace();
				}
				Looper.loop();
			}
		};

		getThreadPool().schedule(task, 0, TimeUnit.MILLISECONDS);
	}

	//获取wifi配置信息
	private void initWifiMsg(){
		new Thread() {
			@Override
			public void run() {
				String wifiMsg = SPAService.getWifiConfig();
				if (!TextUtils.isEmpty(wifiMsg)) {
					try {
						JSONObject jsonObject= new JSONObject(wifiMsg);
						app.wifiName = jsonObject.getString("wifi");
						app.wifiPwd = jsonObject.getString("password");
						EventBus.getDefault().post(new ActionTimeTickEvent());
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}else{
					Log.e("initData", "获取酒店wifi失败.");
				}
			}
		}.start();
	}

	private void initPluginConf() {
		String url = MyApplication.getHost() + SPAService.PROJECT + "/api/plugin.json";
		StringRequest  stringRequest = new StringRequest(Request.Method.GET, url,
				new Response.Listener<String>() {
					@Override
					public void onResponse(String response) {
						Log.i("initData","获取插件配置成功.");
						EventBus.getDefault().post(new UpdateInterfaceEvent(true));
						ModelBean d = gson.fromJson(response, ModelBean.class);
						PluginCfgBean pcb = gson.fromJson(d.getData().toString(), PluginCfgBean.class);
						MyApplication.pluginCfg = pcb.configure;
						setInterfaceMsg();
					}
				}, new Response.ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError error) {
				Log.i("initData", "获取插件配置失败." + error.getMessage());
			}
		});
		stringRequest.setTag("initData");
		stringRequest.setShouldCache(false);
		mQueue.add(stringRequest);
	}

	//存储接口信息
	private void setInterfaceMsg(){
		String ip = InterfaceConfUtil.getConf("jishi","ip","172.16.1.250");
		String port = InterfaceConfUtil.getConf("jishi","port","8081");
		MyApplication.interfaceServerIp = ip;
		MyApplication.interfaceServerPort = port;
		SharedPreferencesConfig.setInterfaceIp(getBaseContext(),ip);
		SharedPreferencesConfig.setInterfacePort(getBaseContext(),port);
	}

	private void initReportMyIP() {
		// 上报IP
		Thread task = new Thread() {
			@Override
			public void run() {
				if (!app.getMyIpAddr().equals("")) {
					SPAService.reportMyIpAddr(MyApplication.getMAC(), app.getMyIpAddr());
					Log.i("initData", "上报IP成功.");
				} else {
					Log.e("initData", "上报IP失败.");
				}
			}
		};
		getThreadPool().schedule(task, 0, TimeUnit.MILLISECONDS);
	}

	private void initDeviceInfo() {
		Thread task= new Thread() {
			@Override
			public void run() {
				try {
					String url = MyApplication.getHost() + SPAService.PROJECT + "/api/equipment-info-mac.json?mac=" + MyApplication.getMAC();
					String result = HttpHelper.getStringSync(null, url);
//					Log.i("plugin", "result=" + result);

					ModelBean d = gson.fromJson(result, ModelBean.class);
					if (!d.getCode().equals(-1) && d.getData() != null) {
						Log.i("initData", "获取设备信息成功.");
						DeviceInfo sb = (DeviceInfo) d.getData(DeviceInfo.class);
						MyApplication.fullDeviceInfo = sb;
					} else {
						Log.i("initData", "获取设备信息失败.");
					}

				} catch (HttpRequestFailException e) {
					Log.e("initData", "获取设备信息失败.");
				}
			}
		};
		getThreadPool().schedule(task, 0, TimeUnit.MILLISECONDS);
	}

	private void getUkeyState() {
		Thread task = new Thread() {
			@Override
			public void run() {
				try {
					String url = MyApplication.getHost() + SPAService.PROJECT + "api/auth.json";
					String result = HttpHelper.getStringSync(null, url);
					Log.i("ukey", "result=" + result);
					/*0	正常
					-1	检查不到U盾！
					-2	验证码错误！
					-3	有效期失效！
					-4	非原装机器！
					-5	系统版本不符！
					其它值	请检查U盾是否插入！*/
					ModelBean d = gson.fromJson(result, ModelBean.class);
					if (d.getCode().equals(0)) {
						Log.i("ukey", "U盾正常！");
					} else if (d.getCode().equals(-1)) {
						Log.i("ukey", "检查不到U盾！");
					}else if (d.getCode().equals(-2)) {
						Log.i("ukey", "验证码错误！！");
					}else if (d.getCode().equals(-3)) {
						Log.i("ukey", "有效期失效！");
						MyApplication.licenseTimeOut = true;
					}else if (d.getCode().equals(-4)) {
						Log.i("ukey", "非原装机器！");
					}else if (d.getCode().equals(-5)) {
						Log.i("ukey", "系统版本不符！");
					}else  {
						Log.i("ukey", "请检查U盾是否插入！");
					}

				} catch (HttpRequestFailException e) {
					Log.e("initData", "获取设备信息失败.");
				}
			}
		};

		getThreadPool().schedule(task, 0, TimeUnit.MILLISECONDS);
	}

	private void initLive() {
		if(Build.BOARD.equals(Constants.BOARD_TYPE_ADA801_NAME) || Build.BOARD.equals(Constants.BOARD_TYPE_ADA628_NAME)
			|| Build.BOARD.equals(Constants.BOARD_TYPE_6A648_NAME) || Build.BOARD.equals(Constants.BOARD_TYPE_ADA648_NAME)){
			new Thread() {
				@SuppressWarnings("unchecked")
				public void run() {
					try {
						Log.i("live","初始化电视节目列表!");

						List<LiveManagement> m_list = SPAService.getLiveList(MyApplication.getMAC());

						File f = new File(Constants.SPA_TV_LIST_FILE_PATH);//这个文件是包括电视节目的名称

						if (m_list == null) {
							List<LiveManagement> list = new Vector<LiveManagement>();
							list = AtvUtil.getTvlistFromLlocal();
							m_list = list;
							Log.e("live", "获取电视列表失败，通过本地的文件生成本地的list");
						} else {
							Log.i("live","通过网络的文件生成本地的list");
							Log.i("live", "获取电视列表成功.");

							// 新建文件-spa使用
							f.createNewFile();
							FileWriter fw = new FileWriter(Constants.SPA_TV_LIST_FILE_PATH);

							for (LiveManagement lm : m_list) {

								fw.write(lm.getPosition() + "-" + lm.getName() + "-" + lm.getFreq() + "-" + lm.getZhishi()
										+ "-" + lm.getRadioZhishi() + "\r\n");
							}

							fw.close();

							f.setReadable(true,false);
							f.setWritable(true,false);
							//把频道列表更新到主板自带电视里面
							AtvUtil.updateChannelList(m_list);
						}

						app.setLiveList(m_list == null ? Collections.EMPTY_LIST : m_list);
					} catch (GetDataException e) {
						Log.e("SPABackService", "SPAService.getLiveList:" + e.getMessage());
						Log.e("initData", "获取电视列表失败:GetDataException");
					} catch (FileNotFoundException e) {
						Log.e("SPABackService", "SPAService.getLiveList:" + e.getMessage());
						Log.e("initData", "获取电视列表失败:FileNotFoundException");
					} catch (IOException e) {
						Log.e("SPABackService", "SPAService.getLiveList:" + e.getMessage());
						Log.e("initData", "获取电视列表失败:IOException");
					}
				};
			}.start();

		}
	}

	// 获取接口类型
	private void initInterfaceType() {
		Thread task = new Thread() {
			@Override
			public void run() {
				//要延时一下，等待系统配置数据获取完成按初始化
				int times = 3;
				try {
					while(!getConfOK && times>0){
						times--;
						Thread.sleep(1000);
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

				Looper.prepare();
				MyApplication.interfaceVersion = null;
				SharedPreferencesConfig.setInterfaceType(getBaseContext(),"");
				try {
					String data = SPAService.getWebAppUrl(MyApplication.getMAC());
					if(TextUtils.isEmpty(data)){
						EventBus.getDefault().post(new UpdateInterfaceEvent(false));
					} else {
						MyApplication.interfaceVersion = data;
						SharedPreferencesConfig.setInterfaceType(getBaseContext(),data);
						Log.i("initData", "获取接口类型成功：" + data);
						initPluginConf();
					}
				} catch (HttpRequestFailException e) {
					Log.e("initData", "获取接口类型失败.");
				}
				Looper.loop();
			}
		};
		getThreadPool().schedule(task, 0, TimeUnit.MILLISECONDS);
	}

	// 本店介绍
	private void initIntro() {
		/*
		 *
		 * 这个不能放到线程池中，否则运行不正常
		 * */
		new Thread() {
			@Override
			public void run() {
				app.setShopIntroduce(SPAService.getAllServeIntroduce(MyApplication.getMAC()));
				if(app.getShopIntroduce() != null){
					EventBus.getDefault().post(new UpdateIntro(true));
				}else{
					EventBus.getDefault().post(new UpdateIntro(false));
				}
			}
		}.start();

	}

	// 命令推送
	private void initServerCmdPush() {

		long interval_time = Integer.parseInt(SysConf.extendConfGetValue(SysConf.SYS_CONF_CMD_GET_INTERVAL, "20000"));
		if(interval_time < 1000){
			interval_time = 1000;
		}
		getThreadPool().scheduleAtFixedRate(new MyCmdTimerTask(), 20000, interval_time, TimeUnit.MILLISECONDS);
	}

	private void initHeartbeat() {

		long interval_time = Integer.parseInt(SysConf.extendConfGetValue(SysConf.SYS_CONF_HEARTRATE, "180000"));

		if(interval_time < 1000){
			interval_time = 1000;
		}
		getThreadPool().scheduleAtFixedRate(new HeartbeatTimerTask(), 0, interval_time, TimeUnit.MILLISECONDS);
	}

	private void initServerTime() {
		getThreadPool().scheduleAtFixedRate(new ServerTimeTimerTask(), 60000, 60000, TimeUnit.MILLISECONDS);
	}

	private void getWeather() {
		int time = 60*60*1000;
		if (app.nowWeather == null){
			time = 20*1000;
		}
		getThreadPool().scheduleAtFixedRate(new WeatherTimerTask(), time, 60*60*1000, TimeUnit.MILLISECONDS);
	}

	private void initRtMsg() {

		long interval_time = Integer.parseInt(SysConf.extendConfGetValue(SysConf.SYS_CONF_RT_MSG_GET_INTERVAL, "1000"));
		if(interval_time < 1000){
			interval_time = 1000;
		}
		TimerTask task = new TimerTask() {
			@Override
			public void run() {
				try {
					String url = MyApplication.getHost() + SPAService.PROJECT + "/api/get-rt-msg.json?mac=" + MyApplication.getMAC();
					StringRequest  stringRequest = new StringRequest(Request.Method.GET, url,
			                 new Response.Listener<String>() {
			                     @Override
			                     public void onResponse(String response) {

			                    	 ModelBean d1 = gson.fromJson(response, ModelBean.class);

			         				if (d1.getCode().equals(-1) || d1.getData() == null || d1.getData().equals(""))
			         					return;

			         				String msg =  d1.getData().toString();

			         				Log.i("rtmsg", "实时消息:" + msg);

			         				if (msg != null) {
			         					app.setRtMsg(msg);
			         					Log.i("rtmsg", msg);
										EventBus.getDefault().post(new UpdateMessageView());
//			         					handlerMsg.sendEmptyMessage(HANDLER_RT_MSG);
			         				}
			                     }
			                 }, new Response.ErrorListener() {
			                     @Override
			                     public void onErrorResponse(VolleyError error) {
			                    	 Log.e("rtmsg", "实时消息获取失败." + error.getMessage());
			                     }
			                 });
					stringRequest.setTag("rtmsg");
					stringRequest.setShouldCache(false);
					mQueue.add(stringRequest);
				} catch (Exception e) {
					Log.e("rtmsg", "SPAService.initRtMsg:" + e.getMessage());
				}
			}
		};
		getThreadPool().scheduleAtFixedRate(task, 20000, interval_time, TimeUnit.MILLISECONDS);
	}

	//定时消息，只处理当天的信息，所以每天凌晨12点要重新获取一次数据，这样就简单点
	private void initTimingMsg() {
		TimerTask task = new TimerTask() {
			@Override
			public void run() {
				try {
					String url = MyApplication.getHost() + SPAService.PROJECT + "/api/time-message.json?mac=" + MyApplication.getMAC();
					//HttpHelper.getStringAsync(getBaseContext(), url, null, handler);
					StringRequest  stringRequest = new StringRequest(Request.Method.GET, url,
			                 new Response.Listener<String>() {
			                     @Override
			                     public void onResponse(String response) {
			                    	 ModelBean d = gson.fromJson(response, ModelBean.class);

			         				if (d != null) {
			         					if (d.getCode().equals(-1) || d.getData() == null || d.getData().equals("")){
			         						Log.i("timingmsg", "实时消息获取失败.");
			         						return;
			         					}
			         					Log.i("timingmsg", "实时消息:" + d.getData());

			         					TimingMsgBean msg[] = (TimingMsgBean[]) d.getData(TimingMsgBean[].class);

			         					List<TimingMsgBean> msgList = Arrays.asList(msg);

			         					if (msgList != null) {
			         						//timingMsg里面的数据，需要在每次
			         						if(MyApplication.timingMsg != null){
			         							MyApplication.timingMsg.clear();
			         							MyApplication.timingMsg.addAll(msgList);

			         							initTimingMsgAlert();
			         							initTimingMsgProcesser();
			         						}
			         					}
			         				}
			         				//处理完这次，初始化下次同步的时间
			         				handlerMsg.sendEmptyMessage(HANDLER_GET_TIMING_MSG);
			                     }
			                 }, new Response.ErrorListener() {
			                     @Override
			                     public void onErrorResponse(VolleyError error) {
			                    	 Log.e("timingmsg", "定时消息获取出错." + error.getMessage());
			                     }
			                 });
					stringRequest.setTag("timingmsg");
					stringRequest.setShouldCache(false);
					mQueue.add(stringRequest);
				} catch (Exception e) {
					Log.e("timingmsg", "initRtMsg:" + e.getMessage());
				}
			}
		};
		getThreadPool().schedule(task, 20000, TimeUnit.MILLISECONDS);
	}


	private void initTimingMsgProcesser() {

		TimerTask task = new TimerTask() {
			@Override
			public void run() {
				int index = 0;
				String[] weekzh ={"星期日","星期一","星期二","星期三","星期四","星期五","星期六"};
				String[] daysZh ={"每月1日","每月2日","每月3日","每月4日","每月5日","每月6日","每月7日"
								,"每月8日","每月9日","每月10日","每月11日","每月12日","每月13日"
								,"每月14日","每月15日","每月16日","每月17日","每月18日","每月19日"
								,"每月20日","每月21日","每月22日","每月23日","每月24日","每月25日"
								,"每月26日","每月27日","每月28日","每月29日","每月30日","每月31日"};
				Calendar calendar = Calendar.getInstance();
				calendar.setTimeInMillis(System.currentTimeMillis());
				String week = weekzh[calendar.get(Calendar.DAY_OF_WEEK)-1];//星期天-星期六
				String days = daysZh[calendar.get(Calendar.DAY_OF_MONTH)-1];//几号
				boolean pushMsg = false;
				while(true){

					if(!MyApplication.timingMsg.isEmpty() && MyApplication.timingMsg.size()>index){
						long currentSystemTick = System.currentTimeMillis();
						TimingMsgBean b = MyApplication.timingMsg.get(index);

						//查看时间是否符合
						if(currentSystemTick >= b.getBeginTimeInMillis() && currentSystemTick <= b.getEndTimeInMillis()){
//							Log.i("timingmsg", "当前系统tick = " + currentSystemTick+ "," +days+week);
//							Log.i("timingmsg", b.getName() + ","+b.getRepeatType()+ ","+b.getContent() + ","+ b.getBeginTimeInMillis() + ","+ b.getEndTimeInMillis());
							if(b.getRepeatType().equals(Constants.REPEATTYPE_EVERY_DAY)){
								//每天的也是要删除的
									pushMsg = true;
								MyApplication.timingMsg.remove(index);
							}else if(b.getRepeatType().equals(Constants.REPEATTYPE_ONE)){
								//只有一次的，发完就删掉
								pushMsg = true;
								MyApplication.timingMsg.remove(index);
							}else if(b.getRepeatType().contains(Constants.REPEATTYPE_WEEK)){
								//处理每个星期几的
								if(week.equals(b.getRepeatType())){
									pushMsg = true;
									MyApplication.timingMsg.remove(index);
								}
							}else if(b.getRepeatType().contains(Constants.REPEATTYPE_MON)){
								//处理每月几号的
								if(days.equals(b.getRepeatType())){
									pushMsg = true;
									MyApplication.timingMsg.remove(index);
								}
							}

							if(pushMsg){
								Message m = new Message();
								m.what = HANDLER_TIMING_MSG;
								Bundle bundle = new Bundle();
								bundle.putString("msg", b.getContent());
								m.setData(bundle);
								handlerMsg.sendMessageDelayed(m, 1000);
							}
						}
					}

					index ++;

					if(MyApplication.timingMsg.size()< index){
						index = 0;
					}

					pushMsg = false;

					try {
						Thread.sleep(3000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		};

		getThreadPool().scheduleAtFixedRate(task, 100, 1000, TimeUnit.MILLISECONDS);
	}

	//初始化一个每天零时获取定时数据的闹钟
	public void initTimingMsgAlert(){
		Log.i("timingmsg", "initTimingMsgAlert");

		Intent intent = new Intent(getBaseContext(), TimingMsgReceiver.class);
		intent.setAction(Constants.Broadcast.TIMING_MSG);
//		PendingIntent pendingIntent = PendingIntent.getService(getBaseContext(), 0, intent, 0);
		PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), 0, intent, 0);
		AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
		// 取消以前同类型的提醒
		alarmManager.cancel(pendingIntent);

		//当前的时间
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(System.currentTimeMillis());


		Calendar calendarNew = Calendar.getInstance();
		calendarNew.setTimeInMillis(System.currentTimeMillis());
//		calendarNew.add(Calendar.HOUR, 24);
		calendarNew.set(Calendar.HOUR_OF_DAY, 23);
		calendarNew.set(Calendar.MINUTE, 59);
		calendarNew.set(Calendar.SECOND, 59);

		// 设定今天0点的时候发出
		Log.i("timingmsg", (calendarNew.getTimeInMillis() - calendar.getTimeInMillis())/1000 + "秒后重新获取定时提醒.");
		alarmManager.set(AlarmManager.RTC_WAKEUP, calendarNew.getTimeInMillis(), pendingIntent);
//		alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),	5*1000, pendingIntent);
	}

	private void initCallStatusSync() {

		int taskPeriod = Integer.parseInt(SysConf.extendConfGetValue(SysConf.SYS_CONF_CALL_SYNC_INTERVAL,"3000"));

		if(taskPeriod < 1000){
			taskPeriod = 1000;
		}
		getThreadPool().scheduleAtFixedRate(new CallStatusSyncTimerTask(), 0, taskPeriod, TimeUnit.MILLISECONDS);
	}

	// 初始化开机导图
	private void initStartUpGuideInfo() {
		new Thread() {
			@Override
			public void run() {
				Looper.prepare();

				try {
					Thread.sleep(15000);
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}

				StartUpGuideInfo logoInfo = null;
				try {
					String url = MyApplication.getHost() + SPAService.PROJECT + "/api/logo.json?mac=" + MyApplication.getMAC();
					String result1 = HttpHelper.getStringSync(null, url);

					Log.i("startUppic", "url =" + url);
					Log.i("startUppic", "result =" + result1);

					if (result1 == null){
						logoInfo = null;
					} else {
						ModelBean d = gson.fromJson(result1, ModelBean.class);

						if (d != null) {
							if (d.getCode().equals(-1) && (d.getData() == null || d.getData().equals(""))){
								logoInfo = null;
							} else if (d.getCode().equals(-2) && (d.getData() == null || d.getData().equals(""))){
								logoInfo = null;
								//删除已经存在的(删整个目录)
								FileUtils.deleteFile(new File(Constants.STARTUP_GUIDE_FILE_PATH));
							} else if (d.getCode().equals(200) && (d.getData() == null || d.getData().equals(""))){
								logoInfo = null;
								Log.i("startupGuide", "引导图被禁止，删除本地开机引导图文件.");
								File f = new File(Constants.STARTUP_GUIDE_FILE_PATH);
								FileUtils.deleteFile(f);
								SharedPreferencesConfig.setStartUpGuideRes(getBaseContext(), "");
							}else {
								StartUpGuideInfo logo = (StartUpGuideInfo) d.getData(StartUpGuideInfo.class);

								if (logo != null) {
									logoInfo = logo;
								}
							}
						}
					}
				} catch (HttpRequestFailException e) {
					Log.e("startUppic", "startUppic数据获取失败:" + e.getMessage());
				}

				if (logoInfo != null && logoInfo.getPath() != null) {
					String name[] = logoInfo.getPath().split("/");

					//获取后缀，重新命令文件
					String tmp[] = name[name.length-1].split("\\.");
					final String fileName = "startupRes." + tmp[1];

					Log.i("startupGuide", "获取到开机引导信息,文件名:" + fileName);
					app.setStartUpGuideInfo(logoInfo);

					if (!app.getStartUpGuideInfo().isEnable()) {
						// 如果禁止了，就删除本地图片
						Log.i("startupGuide", "引导图被禁止，删除本地开机引导图文件.");
						File f = new File(Constants.STARTUP_GUIDE_FILE_PATH);
						FileUtils.deleteFile(f);
						SharedPreferencesConfig.setStartUpGuideRes(getBaseContext(), "");
					} else {
						String downloadPath = MyApplication.getHostResUrl() + "upload/" + app.getStartUpGuideInfo().getPath();
						Log.i("startupGuide", "下载文件path = " + downloadPath);

						////下载新的
						String imageUrl = downloadPath;
						final Bitmap loadImage = ImageUtil.loadImage(getBaseContext(), imageUrl);
						handlerMsg.post(new Runnable() {
							public void run() {
								if (loadImage != null) {
									Log.i("startupGuide", "新开机资源path=" + app.getStartUpGuideInfo().getPath());
									String path = SharedPreferencesConfig.getStartUpGuideRes(getBaseContext());
									String picInfo[] = path.split(",");
									File file = new File(Constants.STARTUP_GUIDE_FILE_PATH + fileName);
									if(picInfo.length == 2 && picInfo[1].endsWith(app.getStartUpGuideInfo().getPath()) && file.exists()){
										Log.i("startupGuide", "文件存在。不需要重新下载");
									} else {
										//删除已经存在的(删整个目录)
										FileUtils.deleteFile(new File(Constants.STARTUP_GUIDE_FILE_PATH));
										//创建目录
										File dir = new File(Constants.STARTUP_GUIDE_FILE_PATH);
										dir.mkdir();
										Log.i("startupGuide", "保存文件到:" + Constants.STARTUP_GUIDE_FILE_PATH + fileName);
										ImageUtil.saveBitmap(loadImage, Constants.STARTUP_GUIDE_FILE_PATH + fileName);
										//保存全路径
										SharedPreferencesConfig.setStartUpGuideRes(getBaseContext(), Constants.STARTUP_GUIDE_FILE_PATH + "/" + fileName + "," +app.getStartUpGuideInfo().getPath());
									}
								}
							}
						});
					}

				} else {
					Log.i("startupGuide", "没有开机引导信息");
				}
				Looper.loop();
			}
		}.start();
	}

	// 初始化主页背景
	private void initBackground() {
		new Thread() {
			@Override
			public void run() {
				Looper.prepare();
				try {
					BackgroundInfo bgInfo = SPAService.getBackground(MyApplication.getMAC());

					if (bgInfo != null) {
						app.setBgInfo(bgInfo);
						Log.i("background", "获取背景成功.");
					} else {
						BackgroundInfo l = new BackgroundInfo();
						l.setStatus(2);
						app.setBgInfo(l);
						Log.i("background", "获取背景失败.");
					}

					if (app.getBgInfo() != null) {
						if (!app.getBgInfo().isEnable()) {
							// 如果禁止了，就删除本地图片
							File f = new File(Constants.BG_FILE_PATH);
							if (f.exists()) {
								Log.i("background", "删除bg文件");
								f.delete();
							}
						} else {
							String imageUrl = MyApplication.getHostResUrl() + "upload/" + app.getBgInfo().getPath();
							final Bitmap loadImage = ImageUtil.loadImage(getBaseContext(), imageUrl);

							if (loadImage != null) {
								Log.i("background", "保存文件到:" + Constants.BG_FILE_PATH);
								MyApplication.setBgBitmap(loadImage);
								ImageUtil.saveBitmap(loadImage, Constants.BG_FILE_PATH);
							}
						}
					}

				} catch (GetDataException e) {
					Log.e("background", "获取背景失败:" + e.getMessage());
				}
				Looper.loop();
			}
		}.start();
	}

	// 初始化其它页面背景
	private void initSeatPic() {
		new Thread() {
			@Override
			public void run() {
				Looper.prepare();
				try {
					SeatPicInfo bgInfo = SPAService.getSeatPicUrl(MyApplication.getMAC());

					if (bgInfo != null) {
						app.setSeatPicInfo(bgInfo);
					} else {
						SeatPicInfo l = new SeatPicInfo();
						l.setStatus(2);
						app.setSeatPicInfo(l);
					}

					if (app.getSeatPicInfo() != null) {
						Log.i("seatPic", "获取刷手牌提示图片成功.");
						if (!app.getSeatPicInfo().isEnable()) {
							// 如果禁止了，就删除本地图片
							File f = new File(Constants.SEAT_FILE_PATH);
							if (f.exists()) {
								Log.i("seatPic", "删除seat文件");
								f.delete();
							}
						} else {
							String imageUrl = MyApplication.getHostResUrl() + "upload/" + app.getSeatPicInfo().getPath();
							final Bitmap loadImage = ImageUtil.loadImage(getBaseContext(), imageUrl);

							if (loadImage != null) {
								Log.i("seatPic", "保存文件到:" + Constants.SEAT_FILE_PATH);
								MyApplication.setSeatBitmap(loadImage);
								ImageUtil.saveBitmap(loadImage, Constants.SEAT_FILE_PATH);
							}
						}
					}else{
						Log.i("seatPic", "获取刷手牌提示图片失败.");
					}
				} catch (GetDataException e) {
					Log.e("seatPic", "SPAService.getBackground:" + e.getMessage());
				}
				Looper.loop();
			}
		}.start();
	}

	//初始化主页logo
	private void initLogo(){
		new Thread() {
			@Override
			public void run() {
				Looper.prepare();

				try {
					Thread.sleep(10000);
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
				String imageUrl = MyApplication.getHostResUrl() + "upload/tv/logo.png";
				Bitmap loadImage = ImageUtil.loadImage(getBaseContext(), imageUrl);

				if (loadImage != null) {
					Log.i("initLogo", "保存文件到:" + Constants.LOGO_FILE_PATH + " &size=" + loadImage.getByteCount());
					MyApplication.setLogoBitmap(loadImage);
					ImageUtil.saveBitmap(loadImage, Constants.LOGO_FILE_PATH);
				}else {
					File f = new File(Constants.LOGO_FILE_PATH);
					if (f.exists()) {
						Log.i("initLogo", "删除logo文件");
						f.delete();
					}
				}
				Looper.loop();
			}
		}.start();
	}

	// 初始化首页主功能图标
	private void initIconAnimation() {
		new Thread() {
			@Override
			public void run() {
				List<IconAnimationDetail> icons = SPAService.getIconAnimation(MyApplication.getMAC());
				if (icons != null) {
					app.setHomeIcon(icons);
				}else{
					Log.e("initData", "获取主页模块图片失败.");
				}
			}
		}.start();
	}

	// 游戏
	private void initAPP() {
		new Thread() {
			@Override
			public void run() {
				Looper.prepare();
				List<AppInfo> appInfos = SPAService.getAppInfos(MyApplication.getMAC());

				if (appInfos != null) {
					app.setAppInfo(appInfos);
					EventBus.getDefault().post(new UpdateGameListEvent(true,"game"));
				}else{
					EventBus.getDefault().post(new UpdateGameListEvent(false,"game"));
				}
				Looper.loop();
			}
		}.start();
	}


	private void initThirdApp() {
		new Thread() {
			@Override
			public void run() {
				try {
					Thread.sleep(1000);
					app.setThirdApps(SPAService.getThirdApp(MyApplication.getMAC()));
					if(app.getThirdApps() != null){
						EventBus.getDefault().post(new UpdateGameListEvent(true,"app"));
					}else{
						EventBus.getDefault().post(new UpdateGameListEvent(false,"app"));
					}
				} catch (InterruptedException e) {
					EventBus.getDefault().post(new UpdateGameListEvent(false,"app"));
				}
			}
		}.start();
	}

	// 获取点播类型
	private void initVod() {

		new Thread() {
			@Override
			public void run() {
				Looper.prepare();
				//采用web做电影页面，获取电影由web来获取了
				if(!SoftwareProperty.isSupportWebPage(SoftwareProperty.WEB_VOD)){
					Log.i("vod", "触摸电视");
					// 获取电影分类列表
					List<Vodpart> vodpart = SPAService.getAllVideosType(MyApplication.getMAC());
					app.setVodpart(vodpart);
					EventBus.getDefault().post(new UpdateVodTypeListEvent());
				}else {

					//获取所有电影的列表，供播放下一集电视剧使用
//				Log.i("vod", "遥控优化");
					Log.i("vod", "获取所有视频..");
					Integer times = 3;
					while (times-- > 0) {
						List<Vodvideo> vods = SPAService.getAllVodList(MyApplication.getMAC());
						if (vods != null) {
							app.vods = vods;
							Log.i("vod", "片源总数 ->>" + app.vods.size());
							break;
						}
					}
				}

				Looper.loop();
			}
		}.start();
	}

	// 获取电视剧类型
	private void initEpisode() {
		new Thread() {
			@Override
			public void run() {
				Looper.prepare();
				// 获取电视剧列表
				List<Episodepart> episode = SPAService.getAllEpisodeType(MyApplication.getMAC());
				app.setVodEpisode(episode);
				if(episode != null){
					EventBus.getDefault().post(new UpdateEpisodeTypeListEvent(true));
				}else{
					EventBus.getDefault().post(new UpdateEpisodeTypeListEvent(false));
				}
				Looper.loop();
			}
		}.start();
	}

	private VodVideoBean removeNotSupportVod(VodVideoBean vvb){

		if(vvb == null ){
//			return vvb;
			return null;
		}

		if(vvb.getMovies() == null ){
			return null;
		}

		List<Vodvideo> vods = new ArrayList<Vodvideo>();
		boolean flag = false;
		for(Vodvideo v : vvb.getMovies()){
			Log.i("vod", "视频最大支持大小为:" + HardwareProperty.getSupportVodSize() + "M,当前视频(" + v.getName() + ")大小为:" + v.getVodSize() + "M");
			if(v.getVodSize() > HardwareProperty.getSupportVodSize()){
				vvb.setTotalRecord(vvb.getTotalRecord() - 1);
//				vvb.getMovies().remove(v);
			} else {
				//验证是否支持电影格式
				String[] format = HardwareProperty.getSupportVodFormat();
				if(format[0].equals("all")){
					vods.add(v);
				}else {
					flag = false;

					for(String suffix : format){
						if(v.getPath() != null && v.getPath().endsWith(suffix)){
							flag = true;
							vods.add(v);
						}
					}

					if(!flag) {
						Log.i("vod", "不支持的视频:" + "(" + v.getPath() + ")");
						vvb.setTotalRecord(vvb.getTotalRecord() - 1);
					}
				}

			}
		}

		vvb.setMovies(vods);

		return vvb;
	}

	// 获取点播类型的视频列表,获取到的数据，设置到vodpart的列表中去
	// posion是类型在vodpart列表的索引
	private void initVodVideo(final Vodpart v) {
		new Thread() {
			@Override
			public void run() {
				Looper.prepare();
				List<Vodpart> vodpart = MyApplication.getVodpart();

				if (vodpart != null && vodpart.size() > 0) {

					// 如果视频列表是空的，就要设置页数为0，从新获取之
					if (v.getVodvideoBeanList() == null)
						v.setNo(0);

					int type = v.getId();
					int no = v.getNo() + 1;
					int size = v.getSize();

					VodVideoBean vvb = SPAService.getVodList(MyApplication.getMAC(), type, no, size, null, null);
					vvb = removeNotSupportVod(vvb);
					if (vvb != null) {

						if (vvb.getTotalRecord() != 0) {
							/* 找到对应的号，并增加上去 */
							int posion = vodpart.indexOf(v);
							vodpart.get(posion).addVodvideoBean(vvb);
							/* 更新页数 */
							vodpart.get(posion).setNo(no);
						}
						/* 通知UI线程更新数据,不管有没有数据 */
						EventBus.getDefault().post(new UpdateVodVideoEvent(true));
					}else{
						EventBus.getDefault().post(new UpdateVodVideoEvent(false));
					}
				} else {
					/* 还没有获取过列表，这里重新获取一下吧 */
					EventBus.getDefault().post(new UpdateVodVideoEvent(false));
				}
				Looper.loop();
			}
		}.start();
	}

	// 获取电视剧类型的视频列表,获取到的数据，设置到Episodepart的列表中去
	// posion是类型在Episodepart列表的索引
	private void initEpisodeVideo(final Episodepart ep) {
		new Thread() {
			@Override
			public void run() {
				Looper.prepare();
				List<Episodepart> episodepart = MyApplication.getVodEpisode();
				if (episodepart != null && episodepart.size() > 0) {

					// 如果视频列表是空的，就要设置页数为0，从新获取之
					int type = ep.getmovieType().getId();

					VodVideoBean vvb = SPAService.getVodList(MyApplication.getMAC(), type, 1, 10000, null, null);
					if (vvb != null) {

						if (vvb.getTotalRecord() != 0) {
								/* 找到对应的号，并增加上去 */
							int posion = episodepart.indexOf(ep);
							episodepart.get(posion).addVodvideoBean(vvb);
								/* 更新页数 */
						}
							/* 通知UI线程更新数据,不管有没有数据 */
						EventBus.getDefault().post(new UpdateEpisodeVideoEvent(true));
					}else{
						EventBus.getDefault().post(new UpdateEpisodeVideoEvent(false));
					}
				} else {
						/* 还没有获取过列表，这里重新获取一下吧 */
					EventBus.getDefault().post(new UpdateEpisodeVideoEvent(false));
				}
				Looper.loop();
			}
		}.start();
	}

	//发起一个视频搜索请求
	private void initVodSearchVideo(final String keys) {
		Thread task = new Thread() {
			@Override
			public void run() {
//				Looper.prepare();

				//搜索就不要使用分页了，太麻烦，直接获取10w部电影~~会所不会有这么多的。。哇哈哈
				VodVideoBean vvb = SPAService.getVodList(MyApplication.getMAC(), 0, 1, 100000, keys, null);
				vvb = removeNotSupportVod(vvb);
				if (vvb != null) {
					app.vodSearchVideos = vvb;
					/* 通知UI线程更新数据,不管有没有数据 */
					EventBus.getDefault().post(new UpdateVodSearchVideoEvent(true));
				}else{
					//没有搜索到
					EventBus.getDefault().post(new UpdateVodSearchVideoEvent(false));
				}

//				Looper.loop();
			}
		};

		getThreadPool().schedule(task, 0, TimeUnit.MILLISECONDS);
	}

	//通过id播放视频
	private void playVideoById(final Integer id,final String idList) {
		new Thread() {
			@Override
			public void run() {
				if(app.vods != null && !app.vods.isEmpty()){
					for(Vodvideo v : app.vods){
//						Log.e("vod", "v.getId()=" + v.getId());
						if(v.getId().equals(id)){
							String url = v.getPath();

							//需要将路径转码，再合并,‘/’斜杠是不需要转码的
							String group[] = url.split("/");
							url = "";
							for(String s : group){
								url += "/";
								try {
									url += URLEncoder.encode(s, "utf-8");
								} catch (UnsupportedEncodingException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
							//////////////////////////
							String tmp[] =  MyApplication.getHostIp().split(":");
							if(tmp.length == 2 && !v.getServerPort().equals("0")){
								url = "http://" + tmp[0] + ":" + v.getServerPort() + "/" + url;
							}else{
								url = MyApplication.getHostResUrl() + url;
							}

							Log.i("vod","云端控制播放电影"+ v.getName() + " url=" + url);

							Intent intent = new Intent(MyApplication.getContext(), CloudAdShowActivity.class);
							intent.putExtra("actionType", "vod");
							intent.putExtra("path", getVideoPathById(id));
							intent.putExtra("filmName", v.getName());
							intent.putExtra("position", v.getPlayPosition());
							intent.putExtra("filmArea", "云推送");
							intent.putExtra("filmId", v.getId());
							intent.putExtra("nextVodsList", idList);
							intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
							startActivity(intent);


						}
					}
				} else {
					Log.e("vod", "app.vods没有数据。。重新获取。。");
					List<Vodvideo> vods = SPAService.getAllVodList(MyApplication.getMAC());
					if(vods != null){
						app.vods = vods;
						Log.i("vod", "片源总数 ->>" + app.vods.size());
					}
				}
			}
		}.start();
	}
	private void playVideoByUrl(final List<Vodvideo> lvv) {
		new Thread() {
			@Override
			public void run() {

				Log.i("vod","云端控制播放电影"+ lvv.get(0).getName() + " url=" + lvv.get(0).getPath());

				Intent intent = new Intent(MyApplication.getContext(), CloudAdShowActivity.class);
				intent.putExtra("actionType", "vod");
				intent.putExtra("path", lvv.get(0).getPath().replaceAll(";", "%3b").replaceAll("\\[", "%5b").replaceAll("\\]", "%5d"));
				intent.putExtra("filmName", lvv.get(0).getName());
				intent.putExtra("position", 0);
				intent.putExtra("filmId", lvv.get(0).getId());
				intent.putExtra("filmArea", "云推送");
				intent.putExtra("list", (Serializable)lvv);
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(intent);

			}
		}.start();
	}
	public static String getVideoPathById(final Integer id) {
//		Log.e("vod", "在app.vod是中查找视频，id=" + id);
		if(app.vods != null && !app.vods.isEmpty()){
			for(Vodvideo v : app.vods){
//				Log.e("vod", "v.getId()=" + v.getId());
				if(v.getId().equals(id)){
					String url = v.getPath().replace(" ", "%20");

					//需要将路径转码，再合并,‘/’斜杠是不需要转码的
					String group[] = url.split("/");
					url = "";
					for(String s : group){
						url += "/";
						try {
							url += URLEncoder.encode(s, "utf-8");
						} catch (UnsupportedEncodingException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					//////////////////////////
					url = url.replace("%2520", "%20");
					String tmp[] =  MyApplication.getHostIp().split(":");
					if(tmp.length == 2 && !v.getServerPort().equals("0")){
						url = "http://" + tmp[0] + ":" + v.getServerPort() + "/" + url;
					}else{
						url = MyApplication.getHostResUrl() + url;
					}

//					Log.i("vod","通过id查找电影->"+ v.getName() + " url=" + url);

					return url;
				}
			}
		} else {
			Log.e("vod", "app.vods没有数据。。重新获取。。");
			List<Vodvideo> vods = SPAService.getAllVodList(MyApplication.getMAC());
			if(vods != null){
				app.vods = vods;
				Log.i("vod", "片源总数 ->>" + app.vods.size());
			}
		}

		return null;
	}

	//获取下一个Vodvideo 对象
	public static Vodvideo getVideoById(final Integer id) {
		Vodvideo nextvod = null;
		List<Vodvideo> nextList = app.vodsList;
		if(nextList != null && !nextList.isEmpty()){
			int nextIndex = -1;
			for(int i =0;i<nextList.size();i++){
				if(nextList.get(i).getId().equals(id)){
					nextIndex = i + 1;
					break;
				}
			}
			if(nextIndex > 0 && nextIndex < nextList.size()){
				nextvod = nextList.get(nextIndex);
			}
		}
		return nextvod;
	}

	public static String getVideoNameById(final Integer id) {
		Log.e("vod", "在app.vods总查找视频，id=" + id);
		if(app.vods != null && !app.vods.isEmpty()){
			for(Vodvideo v : app.vods){
//				Log.e("vod", "v.getId()=" + v.getId());
				if(v.getId().equals(id)){
					return v.getName();
				}
			}
		} else {
			Log.e("vod", "app.vods没有数据。。重新获取。。");
			List<Vodvideo> vods = SPAService.getAllVodList(MyApplication.getMAC());
			if(vods != null){
				app.vods = vods;
				Log.i("vod", "片源总数 ->>" + app.vods.size());
			}
		}

		return null;
	}
	private void initVodPlayStart(final int id) {
		new Thread() {
			@Override
			public void run() {
				try {
					String url = MyApplication.getHost() + SPAService.PROJECT + "/api/movie-time.json?mac="
							+ MyApplication.getMAC() + "&id=" + id;
					Log.i("vod", "start url=" + url);
					SPAService.myHttpPostMsg(url);
				} catch (HttpRequestFailException e) {
					Log.e("vod", e.getMessage());
				}
			}
		}.start();
	}

	private void initVodPlayEnd() {
		new Thread() {
			@Override
			public void run() {
				try {
					String url = MyApplication.getHost() + SPAService.PROJECT + "/api/movie-end.json?mac="
							+ MyApplication.getMAC() + "&ip=" + MyApplication.getHostIp();
					Log.i("vod", "end url=" + url);
					SPAService.myHttpPostMsg(url);
				} catch (HttpRequestFailException e) {
					Log.e("vod", e.getMessage());
				}
			}
		}.start();
	}

	private void msgShowFinish(final int id) {
		new Thread() {
			@Override
			public void run() {
				try {
					String url = MyApplication.getHost() + SPAService.PROJECT + "/api/roll-show-time.json?mac="
							+ MyApplication.getMAC() + "&id=" + id;
					SPAService.myHttpPostMsg(url);
				} catch (HttpRequestFailException e) {
					Log.e("msg", e.getMessage());
				}
			}
		}.start();
	}

	//
	private void adShowFinish(final int id) {
		new Thread() {
			@Override
			public void run() {
				try {
					String url = MyApplication.getHost() + SPAService.PROJECT + "/api/ad-show-time.json?mac="
							+ MyApplication.getMAC() + "&id=" + id;
					SPAService.myHttpPostMsg(url);
				} catch (HttpRequestFailException e) {
					Log.e("ad", e.getMessage());
				}
			}
		}.start();
	}

	// 音乐
	private void updateMusic(GetMusicEvent event) {
		final int fnc = event.GetMusicEventType();
		final int albumId = event.getAlbumId();

		Thread task = new Thread() {
			@Override
			public void run() {
				try {
					if (fnc == Constants.GET_MUSIC_ALBUM_LIST) {
						// 获取专辑数据
						MusicAlbumPageBean musicArea = SPAService.getMusicAlbums(MyApplication.getMAC());
						if(musicArea != null && musicArea.getAlbums().size()>0) {
							app.setMusicArea(musicArea.getAlbums());
							EventBus.getDefault().post(new UpdateMusicEvent(fnc));
						}
					} else if (fnc == Constants.GET_MUSIC_LIST) {
						// 获取音乐列表
						MusicPageBean music = SPAService.getMusics(albumId, MyApplication.getMAC());

						if (music != null) {
							app.setMusicPage(albumId, music);
							EventBus.getDefault().post(new UpdateMusicEvent(fnc));
						}
					}

				} catch (GetDataException e) {
					Log.e("SPABackService", "updateMusic:" + e.getMessage());
					requestFail();
				}


			}
		};

		getThreadPool().schedule(task, 0, TimeUnit.MILLISECONDS);
	}

	private void initYouhuiMessage() {
		Thread task = new Thread() {
			@Override
			public void run() {
				try {
					List<YouhuiMessage> msgs = SPAService.getYouhuiMsg(MyApplication.getMAC());
					if (msgs != null) {
						for (YouhuiMessage message : msgs) {
							System.out.println(message.getTitle());
						}
						app.setMessages(msgs);
						EventBus.getDefault().post(new UpdateYouhuiMsgEvent(true));
					}

				} catch (GetDataException e) {
					EventBus.getDefault().post(new UpdateYouhuiMsgEvent(false));
				}
			}
		};

		getThreadPool().schedule(task, 1, TimeUnit.MILLISECONDS);
	}

	private void initServerVersion(int delayMs) {
		final AsyncHttpResponseHandler handler = new AsyncHttpResponseHandler() {

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {

				if(arg2 != null){
					String result1 = new String(arg2);

					if (result1 != null){
						ModelBean d = gson.fromJson(result1, ModelBean.class);

						if (d != null) {
							if (d.getCode().equals(-1) || d.getData() == null || d.getData().equals("")){
								return;
							}else{
								MyApplication.serverVersion = d.getData().toString();
								Log.i("SPABackService", "获取后台版本完成:v" + d.getData().toString());
							}
						}

					}
				}else{
					Log.i("SPABackService", "获取后台版本失败.");
					initServerVersion(10 * 1000);
				}
			}

			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
				Log.i("SPABackService", "获取后台版本失败.");
				initServerVersion(10 * 1000);
			}
		};

		TimerTask task = new TimerTask() {
			@Override
			public void run() {
				try {
					String url = MyApplication.getHost() + SPAService.PROJECT + "/api/version-sys.json?mac=" + MyApplication.getMAC();
					HttpHelper.getStringAsync(getBaseContext(), url, null, handler);
				} catch (Exception e) {
					Log.e("SPABackService", "SPAService.heartbeat:" + e.getMessage());
				}
			}
		};
		getThreadPool().schedule(task, delayMs , TimeUnit.MILLISECONDS);
	}

	private void initScrollMessage() {
		if(SysConf.extendConfGetValue(SysConf.SYS_CONF_HEAD_DATA_SHOW,"1").equals("1")){
			TOAST_WIDTH = (int) getResources().getDimension(R.dimen.px501);
			TOAST_X = (int) getResources().getDimension(R.dimen.px435);
			TOAST_Y = (int) getResources().getDimension(R.dimen.px6);
		}else {
			TOAST_WIDTH = (int) getResources().getDimension(R.dimen.px1200);
			TOAST_X = (int) getResources().getDimension(R.dimen.px200);
			TOAST_Y = (int) getResources().getDimension(R.dimen.px6);
		}

		toast = new MarqueeToast(getApplicationContext());
		if (handlerMsg.hasMessages(HANDLER_SCROLL_MSG)) {
			handlerMsg.removeMessages(HANDLER_SCROLL_MSG);
		}
		handlerMsg.sendEmptyMessageDelayed(HANDLER_SCROLL_MSG, 15000);

		TimerTask task = new TimerTask() {
			@Override
			public void run() {
				Log.i("msg", "获取滚动消息...");
				try {
					List<ScrollMessage> msgs = SPAService.getscrollMsg(MyApplication.getMAC());
					if (msgs != null) {
						app.setScrollMsg(msgs);
					}

				} catch (GetDataException e) {
					Log.e("SPABackService", "SPAService.getscrollMsg:" + e.getMessage());
					requestFail();
				}
			}
		};
		//时间不能超过10秒。否则会无法显示
		getThreadPool().schedule(task, 10 * 1000 , TimeUnit.MILLISECONDS);
	}

	@Override
	public void run() {
		// Log.i("msg", "showMessage");
//		showMessage();
	}

	public void showMessage() {
		try {
			List<ScrollMessage> localList = app.getScrollMsg();
			if ((localList != null) && (!localList.isEmpty())) {
				if (localList.size() <= messageindex) {
					messageindex = 0;
				}
				if (scrollText != null) {
					scrollText.setLoop(false);
					// scrollText = null;
				}

				if (toast != null) {
					toast.hid();
				}

				// Log.i("msg", localList.get(this.messageindex));

				scrollText = new TextSurfaceView(this, this, true);
				scrollText.setSpeed(12);
				scrollText.setBackgroundColor(0);
				toast.setHeight((int) getResources().getDimension(R.dimen.px66));
				scrollText.setContent(localList.get(messageindex).getContent());
				currentMsgId = localList.get(messageindex).getId();
				toast.setView(scrollText);
				toast.setGravity(Gravity.TOP | Gravity.CENTER, TOAST_WIDTH, TOAST_X, TOAST_Y);
				toast.show();

				// 设置多少秒后停止，停止的事件处理会初始化下一次的滚动消息
				// handler.sendEmptyMessageDelayed(1,
				// getScrollTime(localList.get(messageindex)));

				messageindex++;
			}
		} catch (Exception e) {
			Log.e("msg", e.getMessage());
		}
	}

	@Override
	public void start() {
	}

	@Override
	public void stop() {
		try {
			scrollText.setLoop(false);
			scrollText = null;
			// Looper.prepare();

			// 通知服务器一条滚动消息显示完毕
			if (currentMsgId >= 0) {
				//不用再上报了，没有意义
//				EventBus.getDefault().post(new SetMsgShowFinishEvent(currentMsgId));
			}

			// Log.e("msg", "滚动停止，等待5秒后滚动下一条");
			// new Handler().postDelayed(this, 10000L);
			if (toast != null) {
				toast.hid();
			}
			if (handlerMsg.hasMessages(HANDLER_SCROLL_MSG)) {
				handlerMsg.removeMessages(HANDLER_SCROLL_MSG);
			}

			handlerMsg.sendEmptyMessageDelayed(HANDLER_SCROLL_MSG, 3000);
			// Looper.loop();
			return;
		} catch (Exception localException) {
		}
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public void onDestroy() {
		Log.i("init-SPABackService", "SPABackService onDestroy");
		super.onDestroy();

		if (toast != null) {
			toast.hid();
		}
	}

	private void requestFail() {
		Handler handler = new Handler(Looper.getMainLooper());
		handler.post(new Runnable() {
			@Override
			public void run() {
				// Toast.makeText(SPABackService.this, "网络请求失败.",
				// Toast.LENGTH_LONG).show();
			}
		});
	}

	/* 初始化类滚动字幕 */
	public void onEventMainThread(GetScrollMessage event) {
		new Thread(){
			@Override
			public void run() {
				while (!MyApplication.serverAssess){
					try {
						sleep(5000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				handlerMsg.sendEmptyMessage(INIT_SCROLL_MESSAGE);
			}
		}.start();
	}

	/* 初始化类型列表时使用这个 */
	public void onEventMainThread(GetVodTypeListEvent event) {
		Log.d("SPABackService", "onEventMainThread-->" + "获取视频类别");
		// 点播
		initVod();
	}

	/* 初始化电视剧类型列表时使用这个 */
	public void onEventMainThread(GetVodEpisodeListEvent event) {
		Log.d("SPABackService", "onEventMainThread-->" + "获取电视剧类别");
		// 点播
		initEpisode();
	}

	/* 获取视频点播内容调用这个 */
	public void onEventMainThread(GetVodVideoEvent event) {
		Log.d("SPABackService", "onEventMainThread-->" + "获取视频类别内容");
		// 点播
		initVodVideo(event.vodpart);
	}

	/* 获取电视剧点播内容调用这个 */
	public void onEventMainThread(GetEpisodeVideoEvent event) {
		Log.d("SPABackService", "onEventMainThread-->" + "获取电视剧类别内容");
		// 点播
		initEpisodeVideo(event.episodepart);
	}


	/* 获取视频点播内容调用这个 */
	public void onEventMainThread(GetVodSearchVideoEvent event) {
		Log.d("SPABackService", "onEventMainThread-->" + "搜索视频，关键字:" + event.keys);
		// 点播
		initVodSearchVideo(event.keys);
	}

	/* 获取地区 */
	public void onEventMainThread(GetAreaEvent event) {
		getArea();
	}

	/* 获取天气 */
	public void onEventMainThread(GetWeatherEvent event) {
		getWeather();
	}

	//获取存储的地区
	private void getArea(){
		new Thread(new Runnable() {
			@Override
			public void run() {
				String URL = MyApplication.getHostResUrl() + "/api/dbfile-read.json";
				String request = "filename=WeatherArae";
				Log.i("httpGet", URL + "?" + request);
				String sendRes = HttpRequest.sendGet(URL, request);
				try {
					JSONObject jsObj = new JSONObject(sendRes);
					int code = jsObj.getInt("code");
					String data = jsObj.getString("data");
					if (code == 200 && !TextUtils.isEmpty(data)) {
						JSONObject jsonObject= new JSONObject(data);
						if (!app.areaId.equals(jsonObject.getString("id"))) {
							app.areaId = jsonObject.getString("id");
							app.areaName = jsonObject.getString("name") + ";" + jsonObject.getString("nameEn");
							SharedPreferencesConfig.setAreaId(getBaseContext(),app.areaId);
							SharedPreferencesConfig.setAreaName(getBaseContext(),app.areaName);
							EventBus.getDefault().post(new ActionTimeTickEvent());
						}
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		}).start();
	}

	//获取主页排序
	private void getHomeSort(){
		new Thread(new Runnable() {
			@Override
			public void run() {
				String URL = MyApplication.getHostResUrl() + "/api/dbfile-read.json";
				String request = "filename=HomeIcoSort";
				Log.i("httpGet", URL + "?" + request);
				String sendRes = HttpRequest.sendGet(URL, request);
				try {
					JSONObject jsObj = new JSONObject(sendRes);
					int code = jsObj.getInt("code");
					String data = jsObj.getString("data");
					if (!app.homeSort.equals(data)) {
						app.homeSort = data;
						SharedPreferencesConfig.setHomeSort(app, data);
						EventBus.getDefault().post(new UpdateBottomView());
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		}).start();
	}


	/* 云端播放电影会用到这个 */
	public void onEventMainThread(CloudPlayVideoEvent event) {
		// 点播
//		if(!NetworkUtil.isConnected(MyApplication.getContext())){
			if(event.getId() != null){
				Log.d("SPABackService", "onEventMainThread-->" + "云播放视频，ID:" + event.getId());
				//通过id播放电影
				playVideoById(event.getId(), null);
			} else if(event.getPathList() != null){
				Log.d("SPABackService", "onEventMainThread-->" + "云播放视频，list:" + event.getPathList());
				Pattern pattern = Pattern.compile("\\[.*?\\]");
				Matcher matcher = pattern.matcher(event.getPathList());
				List<Vodvideo> movies = new ArrayList<Vodvideo>();
				Vodvideo vv = new Vodvideo();

				while (matcher.find()) {
					Log.d("SPABackService", "matcher->>:" + matcher.group(0));
					String[] tmp = matcher.group(0).replaceAll("\\[", "").replaceAll("\\]", "").replaceAll("\"", "").split(",");
					vv.setId(Integer.parseInt(tmp[0]));
					vv.setName(tmp[1]);
					vv.setPath(tmp[2].replace(" ", "%20"));

					movies.add(vv);

					Log.i("SPABackService", vv.getId() + "," + vv.getName() + "," + vv.getPath());
			    }

				playVideoByUrl(movies);
				//通过url列表播放电影

			} else if(event.getIdList() != null){
				//铜鼓id列表播放电影
				String tmp[] = event.getIdList().split(",", 2);
				Log.d("SPABackService", "分割列表大小" + tmp.length);
				if(tmp.length > 1){
					Log.d("SPABackService", "1.播放列表->" + tmp[0] + " : " + tmp[1]);
					playVideoById(Integer.valueOf(tmp[0]), tmp[1]);
				} else {
					Log.d("SPABackService", "2.播放列表->" + tmp[0]);
					playVideoById(Integer.valueOf(tmp[0]), null);
				}
			}
		/*}else{
			ToastUtil.showShortToast(MyApplication.getContext(), "网络故障,请先收看电视,稍后再试", 3000);
		}*/
	}

	/* 音乐相关的数据获取事件接口 */
	public void onEventMainThread(GetMusicEvent event) {
		Log.d("SPABackService", "onEventMainThread-->" + "获取音乐数据");

		updateMusic(event);
	}

	/* 游戏相关的数据获取事件接口 */
	public void onEventMainThread(GetGameEvent event) {
		Log.d("SPABackService", "onEventMainThread-->" + "获取游戏,应用列表数据");
		initAPP();
		initThirdApp();
	}

	/* 优惠获取事件接口 */
	public void onEventMainThread(GetYouhuiMsgEvent event) {
		Log.d("SPABackService", "onEventMainThread-->" + "获取优惠信息数据");

		initYouhuiMessage();
	}

	/* 接口地址获取事件接口 */
	public void onEventMainThread(GetWebInterfaceUrlEvent event) {
		Log.d("SPABackService", "onEventMainThread-->" + "获取插件的服务器地址");
		initInterfaceType();
	}

	/* 上报滚动消息显示完成事件接口 */
	public void onEventMainThread(SetMsgShowFinishEvent event) {

		msgShowFinish(event.getId());
	}

	/* 视频相关的获取事件接口 */
	public void onEventMainThread(SetVodPlayEvent event) {

		if (event.getType() == SetVodPlayEvent.START) {
			initVodPlayStart(event.getId());
		} else if (event.getType() == SetVodPlayEvent.END) {
			initVodPlayEnd();
		}
	}

	//发送键码
	public static void setRemoteCode(int code){
		Intent intent = new Intent("com.ly.spa.REMOTE");
		intent.putExtra("code",code);
		intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
		MyApplication.getContext().sendBroadcast(intent);
	}

	/* 广告播放完毕事件接口 */
	public void onEventMainThread(AdShowFinishEvent event) {

		adShowFinish(event.getId());
	}

	public void onEventMainThread(GetTimingMsgEvent event) {

		initTimingMsg();
	}

	public void onEventMainThread(GetIntro event) {
		initIntro();
	}
	/* 广告播放完毕事件接口 */
	public void onEventMainThread(SyncCallEvent event) {
		/*try{
			if(callStatus_timer != null){
				callStatus_timer.cancel();
				callStatus_timer = new Timer(true);
			}else{
				callStatus_timer = new Timer(true);
			}
		}catch (Exception e){
			Log.i("call", "新建呼叫同步任务");
		}

		initCallStatusSync();*/
	}

	/* 滚动消息弹窗接口 */
	public void onEventMainThread(MsgDialogEvent event) {
		if (event.getAction() == MsgDialogEvent.ACTION_SHOW) {
			Message msg = new Message();
			Bundle bundle = new Bundle();
			bundle.putString("msg", event.getMsg());

			msg.what = event.getId();
			msg.setData(bundle);
			handlerMsg.sendMessageDelayed(msg, event.getDelayTime());

			// 放进窗口队列
			putMsgId(msg.what);
		} else if (event.getAction() == MsgDialogEvent.ACTION_CLOSE) {
			if (event.getId() != null && !event.getId().equals(0)) {
				closeMsgActivity(event.getId());
			}
		}
	}

	// 在队列中插入一个id，这时候activity还没有创建的，需要创建之后使用putMsgActivity再次初始化
	public void putMsgId(Integer id) {
		if (!id.equals(0)) {
			msgActivity.put(id, null);
		}
	}

	public static void putMsgActivity(Integer id, MsgDialog c) {
		if (c != null && !id.equals(0)) {
			msgActivity.put(id, c);
		}
	}

	public void closeMsgActivity(Integer id) {
		if (id != null && !id.equals(0)) {
			// 如果还没有创建的，就将信息从handler中去掉
			handlerMsg.removeMessages(id);

			// 如果已经创建了的,就同时关闭这个窗口
			if (msgActivity.get(id) != null) {
				msgActivity.get(id).dismiss();
			}

			// 从hash表中去掉这个窗口信息
			msgActivity.remove(id);
		}
	}

	private static class ThisHandler extends Handler {
		private WeakReference<SPABackService> wrActivity;

		public ThisHandler(SPABackService activity) {
			wrActivity = new WeakReference<SPABackService>(activity);
		}

		@Override
		public void handleMessage(Message message) {
			SPABackService act = wrActivity.get();
			if (act != null) {
				// 这个是通过事实消息接口获取的弹窗信息打开的
				if(message.what == HANDLER_CHECK_SERVER){
					act.checkServerAlive();
				}else if(message.what == HANDLER_INIT){
					/*通过线程初始化的*/
					act.initSysSetting();
					act.initIconAnimation();		// 首页模块图片
					act.initServerApiVersion();
					act.initCloud();
					act.initDeviceInfo();
					act.getHomeSort();

					act.initServerVersion(0);		//获取服务器版本
					act.initStartUpGuideInfo();		// 获取开机帮助图
					act.initBackground();
					act.initSeatPic();
					act.initLogo();
					act.initLive();					// 直播数据
					act.initInterfaceType();
					act.initExpConf();
					act.initWifiMsg();
					act.getArea();

					/*通过ScheduledExecutorService线程池定时获取的*/
					act.initHeartbeat();			// 初始化心跳
					act.initServerCmdPush();		// 服务器推送命令
					act.initServerTime();			// 服务器时间
					act.getWeather();
//					act.initScrollMessage();		// 滚动消息
					act.initRtMsg();				// 实时消息
					act.initTimingMsg();			// 定时消息
					act.initCallStatusSync();		// 初始化一个定时器，不断刷新呼叫状态
					act.getUkeyState();				// 获取U盾是不是过期了
					act.initCoBoard();				// 初始化协处理板
					act.initGetLocalIp();			// 获取本地IP
					
				}else if (message.what == HANDLER_SCROLL_MSG) {
					//滚动消息
					act.showMessage();
				}else if (message.what == HANDLER_RT_MSG) {
					/*Log.i("rtmsg", "实时消息");
					if(SPABackService.app.getRtMsgList().get(0).startsWith("window:")){
						Log.i("rtmsg", "弹窗类型");
						// 实时消息的弹窗会调用这个
						MsgDialog dialog = new MsgDialog(act, R.style.msgDialog);// 创建Dialog并设置样式主题
						dialog.setMsg(SPABackService.app.getRtMsgList().get(0).replaceFirst("window:", ""));
						dialog.setId(msgActivityid++);
						dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
						dialog.show();
						SPABackService.app.removeRtMsg(0);
					}else{
						Log.i("rtmsg", "普通实时消息");
						MsgDialog dialog = new MsgDialog(act, R.style.msgDialog);// 创建Dialog并设置样式主题
						dialog.setMsg(SPABackService.app.getRtMsgList().get(0));
						dialog.setId(msgActivityid++);
						dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
						dialog.show();
						SPABackService.app.removeRtMsg(0);
					}*/
					
				} else if(message.what == HANDLER_TIMING_MSG){
					TimingMsgDialog dialog = new TimingMsgDialog(act, R.style.msgDialog);// 创建Dialog并设置样式主题
					dialog.setMsg(message.getData().getString("msg"));
					dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
					dialog.getWindow().setGravity(Gravity.TOP);
					dialog.show();
				} else if (message.what >= MSG_ACTIVITY_BEGIN_ID) {
					Log.i("rtmsg", "LyAgent弹窗");
					// lyAgent接口弹窗的信息，会调用这个，每一个弹窗的what是不一样的
					MsgDialog dialog = new MsgDialog(act, R.style.msgDialog);// 创建Dialog并设置样式主题
					dialog.setMsg(message.getData().getString("msg"));
					dialog.setId(message.what);
					dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
					dialog.show();
//					SPABackService.app.removeRtMsg(0);

				} else if(message.what == INIT_CO_BOARD){//初始化协处理板
					byte[] b = {'n','u','l',(byte)0x0a,(byte)0x0d};
					byte[] bb = {'s','l','e','d',',','o','f','f',(byte)0x0a,(byte)0x0d};
					byte[] bbb = {'l','l','e','d',',','o','f','f',(byte)0x0a,(byte)0x0d};
					if(MyApplication.isLogined()){
						try {
							Log.v("co-board", "初始化协处理板，复位留位及服务灯到关闭状态.");
							//先发测试数据，打通串口
							if(Build.BOARD.endsWith(Constants.BOARD_TYPE_ADA801_NAME)){
								if(HandNoBinder.sp2 != null){
									HandNoBinder.sp2.getSerialPort().getOutputStream().write(b);
									HandNoBinder.sp2.getSerialPort().getOutputStream().flush();
								}
							} else if(Build.BOARD.endsWith(Constants.BOARD_TYPE_ADA628_NAME)){
								if(HandNoBinder.sp != null){
									HandNoBinder.sp.getSerialPort().getOutputStream().write(b);
									HandNoBinder.sp.getSerialPort().getOutputStream().flush();
								}
							} else if(Build.BOARD.endsWith(Constants.BOARD_TYPE_6A648_NAME) ||
									Build.BOARD.equals(Constants.BOARD_TYPE_ADA648_NAME)){
								if(HandNoBinder.sp2 != null){
									HandNoBinder.sp2.getSerialPort().getOutputStream().write(b);
									HandNoBinder.sp2.getSerialPort().getOutputStream().flush();
								}
							} 
							//关服务灯
							if(Build.BOARD.endsWith(Constants.BOARD_TYPE_ADA801_NAME)){
								if(HandNoBinder.sp2 != null){
									HandNoBinder.sp2.getSerialPort().getOutputStream().write(bb);
									HandNoBinder.sp2.getSerialPort().getOutputStream().flush();
								}
							} else if(Build.BOARD.endsWith(Constants.BOARD_TYPE_ADA628_NAME)){
								if(HandNoBinder.sp != null){
									HandNoBinder.sp.getSerialPort().getOutputStream().write(bb);
									HandNoBinder.sp.getSerialPort().getOutputStream().flush();
								}
							}  else if(Build.BOARD.endsWith(Constants.BOARD_TYPE_6A648_NAME) ||
									Build.BOARD.equals(Constants.BOARD_TYPE_ADA648_NAME)){
								if(HandNoBinder.sp2 != null){
									HandNoBinder.sp2.getSerialPort().getOutputStream().write(bb);
									HandNoBinder.sp2.getSerialPort().getOutputStream().flush();
								}
							}
							//关留位灯
							if (MyApplication.myLicenseGetValue("留位").equals(1)){
								//如果电视有留位功能，才复位留位
								if(Build.BOARD.endsWith(Constants.BOARD_TYPE_ADA801_NAME)){
									if(HandNoBinder.sp2 != null){
										HandNoBinder.sp2.getSerialPort().getOutputStream().write(bbb);
										HandNoBinder.sp2.getSerialPort().getOutputStream().flush();
									}
								} else if(Build.BOARD.endsWith(Constants.BOARD_TYPE_ADA628_NAME)){
									if(HandNoBinder.sp != null){
										HandNoBinder.sp.getSerialPort().getOutputStream().write(bbb);
										HandNoBinder.sp.getSerialPort().getOutputStream().flush();
									}
								}  else if(Build.BOARD.endsWith(Constants.BOARD_TYPE_6A648_NAME) ||
										Build.BOARD.equals(Constants.BOARD_TYPE_ADA648_NAME)){
									if(HandNoBinder.sp2 != null){
										HandNoBinder.sp2.getSerialPort().getOutputStream().write(bbb);
										HandNoBinder.sp2.getSerialPort().getOutputStream().flush();
									}
								}
							}
						} catch (IOException e) {
							e.printStackTrace();
							act.handlerMsg.sendEmptyMessageDelayed(INIT_CO_BOARD, 3000);
						}
	
					}else{
						act.handlerMsg.sendEmptyMessageDelayed(INIT_CO_BOARD, 3000);
					}

				} else if(message.what == SEND_CO_BOARD_HEART){//发送心跳包给协处理板
					//发送心跳给协处理板
					byte[] bi = {'s','m','a','r','t','t','v',(byte)0x0a,(byte)0x0d};
					
					if(MyApplication.isLogined() && NetworkUtil.isConnectednoLog(act)){
						try {
							if(Build.BOARD.endsWith(Constants.BOARD_TYPE_ADA801_NAME)){
								Log.v("co-board", "发送心跳到协处理板");
								if(HandNoBinder.sp2 != null){
									HandNoBinder.sp2.getSerialPort().getOutputStream().write(bi);
									HandNoBinder.sp2.getSerialPort().getOutputStream().flush();
								}
							} else if(Build.BOARD.endsWith(Constants.BOARD_TYPE_ADA628_NAME)){
								Log.v("co-board", "发送心跳到协处理板");
								if(HandNoBinder.sp != null){
									HandNoBinder.sp.getSerialPort().getOutputStream().write(bi);
									HandNoBinder.sp.getSerialPort().getOutputStream().flush();
								}
							}  else if(Build.BOARD.endsWith(Constants.BOARD_TYPE_6A648_NAME) ||
									Build.BOARD.equals(Constants.BOARD_TYPE_ADA648_NAME)){
								Log.v("co-board", "发送心跳到协处理板");
								if(HandNoBinder.sp2 != null){
									HandNoBinder.sp2.getSerialPort().getOutputStream().write(bi);
									HandNoBinder.sp2.getSerialPort().getOutputStream().flush();
								}
							}
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
					
					act.handlerMsg.sendEmptyMessageDelayed(SEND_CO_BOARD_HEART, 3000);
				}else if(message.what == INIT_SCROLL_MESSAGE){
					act.initScrollMessage();
				}
			}
		}
	}

}
